// React基础组件
import React from 'react'
// dva 连接组件 - 连接route和model
import { connect } from 'dva'
import moment from 'moment'
// 引入antd的组件
import {
  Form,
  Row,
  Col,
  Input,
  DatePicker,
  Upload,
  message,
  Select,
  Button,
  Modal,
  Popconfirm,
  Tooltip,
  Icon ,
  Checkbox
} from 'antd'
//导入路由组件，用于跳转等
import { Link, hashHistory } from 'dva/router'
// 导入项目全局配置文件
import config from 'config/config'
// import {  isEmpty, isArray, cloneDeep, chunk,  set } from 'lodash'
// import Cookie from 'js-cookie'
// 引入model取值工具方法
import { mapStateToProps } from 'utils/view_utils'
// import { reg } from 'utils/util'
// 当前组件样式
import styles from './commissionsDistRulesDetailStyle.less'

import ListPage from 'widget/PageTmpl/ListPage'
import Uploader from 'widget/Upload'
import { CollapsiblePanels } from 'widget/CollapsiblePanels/index'
import { Grid, QueryCondition } from 'widget/Grid/index'
import classnames from 'classnames/bind'
let cx = classnames.bind(styles);

const FormItem = Form.Item
const { TextArea } = Input;
// const { RangePicker } = DatePicker;

const formItemLayout = {
  labelCol: { span: 8 },
  wrapperCol: { span: 15 },
}
const formItemLayout01 = {
  labelCol: { span: 4 },
  wrapperCol: { span: 20 },
}


/**
 * description 路由视图及事件处理
 * dispatch 分发到models中的effects对应事件名
 * model 用于获取models中state定义的数据
 * form 表单对象
 */
const commissionsDistRulesDetailView = function ({ dispatch, model, form }) {
  // 表单的子函数
  const { getFieldDecorator, validateFieldsAndScroll,setFieldsValue,getFieldsValue} = form
  // 取出model对象，命名空间
  const { modelObj, namespace } = model
  let {productDataList,searchData,productListObj,productPageConfig,projectFilterParams, submitType,fileModalObj,distCoId,url,uploadFileObj,imageUrls,biz1,biz2,biz3,biz4,formatsKey,biz,tableObj,actionType, id,keys,distributionNameList, projectModalObj,codeModalObj,enclosureNameModalObj,tableData, pageConfig, loading, selectedRowKeys, formatsModalObj,detail} = modelObj
  // modelObj.xxx获取model中状态机的值
  let pageProps2 = {   //项目名称
    // ---------- 界面部分 ----------
    ui: {
      // 页面接口地址
      api_url: `3rd/commission/queryProjectHead`,
      // 接口方式
      method: 'POST',
      headers: {
        'Content-type': 'application/json'
      },
      app: '',
      // 接口参数
      params: {
        "pageSize":10,
        "pageNo":1,
        projectId:projectFilterParams
      },
      // 模拟数据 - 用于开发需要，若填充了上面的api_url之后，请将此项设置为null
      // "mockData": mockData,
      mockData: null,

      selectedRowKeys:'',
      // 查询栏
      search_bar: {
        fields: [
          {
            en_name: 'projectName',
            zh_name: '项目名称',
            elem_type: 'Input',
            elem_valid_type: 'string',
          },
        ],
        searchHandler: (e) => { // 自定义搜索按钮回调函数，点击搜索时触发
          console.log('search click', e)
        },
        resetHandler: () => { // 自定义重置按钮回调函数，点击重置时触发
          console.log('reset click')
        },
        searchCallback: params => { // 自定义搜索完成后的后调函数, 搜索完成后触发, 并将本次搜索的参数传入
          console.log('search finish', params)
        },
        pasteTargetList: [  // 列表组件中将输入框的en_name作为默认id(也可以通过id另外设置)
          'carName',  // 将需要粘贴事件拦截的输入框id以数组的形式传入, 该参数对应PasteFromClipboard组件的targetList参数
        ]
      },
      // 数据表格
      'table':
        {
          rowSelectionInfo: {
            type: 'radio',
          },
          status_params: 'status=0',
          status_text: '全部',
          // 表头字段列表
          scroll: {x: 800},
          fields: [
            {
              en_name: 'regionName',
              zh_name: '区域公司',
              // width: 100,
            },
            {
              en_name: 'projectName',
              zh_name: '项目名称',
              // width: 100,
            },
            {
              en_name: 'projectId',
              zh_name: '项目ID',
              width: 180
            },
          ],
          // 表格操作
          actions: [],
        },
      action_bar: [
        {
          // label:'',
          // type:'',
          rowSelection: [],
          render: () => {
            return <Input hidden/>
          },
          onClick: (e, row) => {
          }
        },
      ]
    },
  }
  let pageProps3 = {   //合同编号
    // ---------- 界面部分 ----------
    ui: {
      // 页面接口地址
      api_url: `admin/commissionRule/srmExportConContractInfo`,
      // 接口方式
      method: 'POST',
      headers: {
        'Content-type': 'application/json'
      },
      app: '',
      // 接口参数
      params:  {
        "pageSize":10,
        "pageNo":1,
        regionName: detail.regionName,
      },
      // 模拟数据 - 用于开发需要，若填充了上面的api_url之后，请将此项设置为null
      // "mockData": mockData,
      mockData: null,

      selectedRowKeys:'',
      // 查询栏
      search_bar: {
        fields: [
          {
            en_name: 'contractDesc',
            zh_name: '合同名称',
            elem_type: 'Input',
            elem_valid_type: 'string',
          },
          {
            en_name: 'venderDesc',
            zh_name: '供应商名称',
            elem_type: 'Input',
            elem_valid_type: 'string',
          },
        ],
        searchHandler: (e) => { // 自定义搜索按钮回调函数，点击搜索时触发
          console.log('search click', e)
        },
        resetHandler: () => { // 自定义重置按钮回调函数，点击重置时触发
          console.log('reset click')
        },
        searchCallback: params => { // 自定义搜索完成后的后调函数, 搜索完成后触发, 并将本次搜索的参数传入
          console.log('search finish', params)
        },
        pasteTargetList: [  // 列表组件中将输入框的en_name作为默认id(也可以通过id另外设置)
          'carName',  // 将需要粘贴事件拦截的输入框id以数组的形式传入, 该参数对应PasteFromClipboard组件的targetList参数
        ]
      },
      // 数据表格
      'table':
        {
          rowSelectionInfo: {
            type: 'checkbox',
          },
          status_params: 'status=0',
          status_text: '全部',
          // 表头字段列表
          scroll: {x: 800},
          fields: [
            {
              en_name: 'contractDesc',
              zh_name: '合同名称',
              width: 180,
            },
            {
              en_name: 'documentDesc',
              zh_name: '合同编号',
            },
            {
              en_name: 'contractStartDate',
              zh_name: '合同有效起',
            },
            {
              en_name: 'contractEndDate',
              zh_name: '合同有效止',
            },
            {
              en_name: 'contractCreateby',
              zh_name: '创建人名称',
            },
            {
              en_name: 'venderDesc',
              zh_name: '供应商名称',
            },
          ],
          // 表格操作
          actions: [],
        },
      action_bar: [
        {
          // label:'',
          // type:'',
          rowSelection: [],
          render: () => {
            return <Input hidden/>
          },
          onClick: (e, row) => {
          }
        },
      ]
    },
  }
  let pageProps4 = {   //关联附件
    // ---------- 界面部分 ----------
    ui: {
      // 页面接口地址
      api_url: `admin/commissionRule/queryAsbeginPage`,
      // 接口方式
      method: 'POST',
      headers: {
        'Content-type': 'application/json'
      },
      app: '',
      // 接口参数
      params:  {
        "pageSize":10,
        "pageNo":1,
        projectId: detail.projectId
      },
      // 模拟数据 - 用于开发需要，若填充了上面的api_url之后，请将此项设置为null
      // "mockData": mockData,
      mockData: null,

      selectedRowKeys:'',
      // 查询栏
      search_bar: {
        fields: [
          {
            en_name: 'fileName',
            zh_name: '附件名称',
            elem_type: 'Input',
            elem_valid_type: 'string',
          },
        ],
        searchHandler: (e) => { // 自定义搜索按钮回调函数，点击搜索时触发
          console.log('search click', e)
        },
        resetHandler: () => { // 自定义重置按钮回调函数，点击重置时触发
          console.log('reset click')
        },
        searchCallback: params => { // 自定义搜索完成后的后调函数, 搜索完成后触发, 并将本次搜索的参数传入
          console.log('search finish', params)
        },
        pasteTargetList: [  // 列表组件中将输入框的en_name作为默认id(也可以通过id另外设置)
          'fileName',  // 将需要粘贴事件拦截的输入框id以数组的形式传入, 该参数对应PasteFromClipboard组件的targetList参数
        ]
      },
      // 数据表格
      'table':
        {
          rowSelectionInfo: {
            type: 'checkbox',
          },
          status_params: 'status=0',
          status_text: '全部',
          // 表头字段列表
          scroll: {x: 800},
          fields: [
            {
              en_name: 'fileName',
              zh_name: '附件名称',
              width: 180,
            },
            {
              en_name: 'createTime',
              zh_name: '上传时间',
            },
            {
              en_name: 'createBy',
              zh_name: '上传人账号',
            },
            {
              en_name: 'createByName',
              zh_name: '上传人名称',
            },
          ],
          // 表格操作
          actions: [],
        },
      action_bar: [
        {
          // label:'',
          // type:'',
          rowSelection: [],
          render: () => {
            return <Input hidden/>
          },
          onClick: (e, row) => {
          }
        },
      ]
    },
  }
  // 表格配置------------开始
  // 序号  分销公司名称 业态名称 结佣方式 套数范围（套） 金额范围（万元） 比列（%）  固定金额  规则生效日期 规则失效日期 合同编码 备注
  // 序号  分销公司名称 业态名称 结佣方式 套数范围（套） 金额范围（万元） 比列（%）  固定金额  规则生效日期 规则失效日期 合同编码 备注
  const columns1 = [
    {
      title: '分销公司名称', dataIndex: 'distCoName', key: 'distCoName', width: 240,
      render: function (value, item, index) {
        return <div onClick={() => { onQueryAgent(value,item,index) }}>
          {/* <Select disabled={actionType == 'check'} value={item.distCoName} placeholder="请选择分销公司名称" onChange={(e)=>{tableChange(e,'distCoName',item.key)}}>
               { distributionNameList == undefined ?null:distributionNameList.map((itemed,index)=>{
                  return <Select.Option value={itemed.orgName} key={index}>{itemed.orgName}</Select.Option>
                })}
          </Select> */}
          <FormItem style={{marginBottom: 0}}>
                {getFieldDecorator(`distCoName_${index}`, {
                    rules: [{
                      required: (item.distCoName||detail.noCommission) ? false:true,whitespace: true, message: '请选择分销公司名称'
                    }],
                    initialValue: item.distCoName,
                })(
                  <Select disabled={actionType == 'check'} placeholder="请选择分销公司名称" onChange={(e)=>{tableChangeDistCoId(e,'distCoName',item.key)}}>
                        { distributionNameList == undefined ?null:distributionNameList.map((itemed,key)=>{
                          return <Select.Option value={itemed.orgName} key={key}>{itemed.orgName}</Select.Option>
                        })}
                  </Select>
                )}
            </FormItem>
      </div>
      }
    },
    {
      title: '业态名称', dataIndex: 'productName', key: 'productName', width: 200,
      render: function (value, item, index) {
        return <div>
          <Input value = {item.productName} disabled={actionType == 'check'} readOnly={true}
                placeholder={'请输入业态名称'}
                onChange={(e) => { tableChange(e.target.value, 'productName',item.key) }}
                onClick={() => { updateFormatsName(value,item,index) }}
              />
        </div>
      }
    },
    {
      title: '结佣方式', dataIndex: 'commTypeName', key: 'commTypeName', width: 200,
      render: function (value, item, index) {
     
        return <div>
            <Select disabled={actionType == 'check'} placeholder="请选择结佣方式" value={item.commTypeName}   onChange={(e)=>{tableChangeCommType(e,'commTypeName',item.key)}}>
                <Select.Option style={{display: item.intertemporal == 2&&detail.computeNodes != 2?'none':'block'}} value="按套数跳点">按套数跳点</Select.Option>
                <Select.Option style={{display: item.intertemporal == 2&&detail.computeNodes != 2?'none':'block'}} value="按金额跳点">按金额跳点</Select.Option>
                <Select.Option value="按固定金额">按固定金额</Select.Option>
                <Select.Option value="按固定比例">按固定比例</Select.Option>
                <Select.Option value="按套数跳固额">按套数跳固额</Select.Option>
            </Select>
    </div>
      }
    },
    {
      title: '跨期处理', dataIndex: 'intertemporal', key: 'intertemporal', width: 200,
      render: function (value, item, index) {
        return <div>
            <Select disabled={actionType == 'check'||detail.computeNodes == 2||detail.computeNodes == 3} placeholder="请选择跨期处理方式" value={detail.computeNodes == 1&&item.intertemporal?item.intertemporal+'':'0'}   onChange={(e)=>{tableChange(e,'intertemporal',item.key)}}>
                <Select.Option value="0">默认（无）</Select.Option>
                <Select.Option value="1">当期认购当期签约</Select.Option>
                <Select.Option value="2">当期认购跨期签约</Select.Option>
            </Select>
    </div>
      }
    },
    {
      title: () => (
        <span>
          {'套数范围（套）'}
          {/* <Tooltip
              title={'数值为左闭右开原则，即： 大于等于左边，小于右边的值。若右边值为空，则表示大于等于左边值。'}
          >
            <Icon style={{ marginLeft: 8 }} type="question-circle" />
          </Tooltip> */}
          <div style={{color:'red'}}>{"注：左边值≤ X <右边值"}</div>
        </span>
      ), className: 'colum-tips' ,dataIndex: 'numberStart', key: 'numberStart', width: 210,
      render: function (value, item, index) {
        return <div className={cx('flex')}>
            <Input disabled={actionType == 'check' || item.commTypeName == '按金额跳点'||item.commTypeName == '按固定金额'||item.commTypeName == '按固定比例'}  value = {item.numberStart}
                onChange={(e) => { tableChange(e.target.value.replace(/[^\-?\d.]/g,''), 'numberStart',item.key) }}
              />
            <span>~</span>
            <Input disabled={actionType == 'check' || item.commTypeName == '按金额跳点'||item.commTypeName == '按固定金额'||item.commTypeName == '按固定比例'}   value = {item.numberEnd}
                onChange={(e) => { tableChange(e.target.value.replace(/[^\-?\d.]/g,''),'numberEnd',item.key) }}
              />
        </div>
      }
    },
    {
      title: '金额范围（万元）', dataIndex: 'amountStart', key: 'amountStart', width: 210,
      render: function (value, item, index) {
        return <div className={cx('flex')}>
          <Input disabled={actionType == 'check' || item.commTypeName != '按金额跳点'} value = {item.amountStart}
              onChange={(e) => { tableChange(e.target.value.replace(/[^\-?\d.]/g,''), 'amountStart',item.key) }}
            />
          <span>~</span>
          <Input disabled={actionType == 'check'  || item.commTypeName != '按金额跳点'} value = {item.amountEnd}
              onChange={(e) => { tableChange(e.target.value.replace(/[^\-?\d.]/g,''), 'amountEnd',item.key) }}
            />
      </div>
      }
    },
    {
      title: '比例（%）', dataIndex: 'ratioNum', key: 'ratioNum', width: 120,
      render: function (value, item, index) {
        return <div>
          <Input value = {item.ratioNum} disabled={actionType == 'check' || item.commTypeName == '按固定金额' || item.commTypeName == '按套数跳固额'|| !item.commTypeName}
              onChange={(e) => { tableChange(e.target.value.replace(/[^\-?\d.]/g,''), 'ratioNum',item.key) }}
            />
        </div>
      }
    },
    {
      title: '固定金额', dataIndex: 'amount', key: 'amount', width: 160,
      render: function (value, item, index) {
        return <div>
        <Input value = {item.amount} disabled={actionType == 'check' || item.commTypeName == '按固定比例' || item.commTypeName == '按套数跳点'|| item.commTypeName == '按金额跳点' || !item.commTypeName}
            onChange={(e) => { tableChange(e.target.value.replace(/[^\-?\d.]/g,''), 'amount',item.key) }}
          />
      </div>
      }
    },
    {
      title: '规则生效日期', dataIndex: 'startTime', key: 'startTime', width: 200,
      render: function (value, item, index) {
        return <div>
                <DatePicker disabledDate={(current)=>disabledDate(current)} style={{width: 170 }}  disabled={actionType == 'check'} format="YYYY-MM-DD"  value={item.startTime? moment(item.startTime, 'YYYY-MM-DD') : null}  onChange={(e, val) => tableChange(val, 'startTime',item.key)} />
              </div>
      }
    },
    {
      title: '规则失效日期', dataIndex: 'endTime', key: 'endTime', width: 200,
      render: function (value, item, index) {
        return <div>
                <DatePicker disabledDate={(current)=>disabledDate(current)} style={{width: 170 }}  disabled={actionType == 'check'}  format="YYYY-MM-DD"  value={item.endTime? moment(item.endTime, 'YYYY-MM-DD') : null}  onChange={(e, val) => tableChange(val, 'endTime',item.key)} />
              </div>
      }
    },
    {
      title: '合同编号', dataIndex: 'contractId', key: 'contractId', width: 200,
      render: function (value, item, index) {
        if(item.contractList&&item.contractList.length){
          return <div>
            {item.contractList.map(function(ikk,key2){
              return  <div className={cx('flex')} key={key2}>
                          <span className={cx('span_overflow_omit')} onClick={() => { updateFileModal(value,ikk,index,'contractId') }}>{ikk.contractId}</span>
                          <span style={{display: (item.id&&actionType == 'check') ? "none" : "block"}} className={cx('red_del_style')}  onClick={() => { delCodeName('表格数据',item,ikk) }}>X</span>
                    </div>
              })}
          </div>
        }else{
          return <Button disabled={actionType == 'check'}  onClick={() => { updateCodeName(value,item,index) }} type="link">选择</Button>
        }
      }
    },
    {
      title: '关联附件', dataIndex: 'enclosureName', key: 'enclosureName', width: 200,
      render: function (value, item, index) {
        if(item.enclosureList&&item.enclosureList.length){
          return <div>
           {item.enclosureList.map(function(ik,keyy){
            return <div className={cx('flex')} key={keyy}>
                        <span  className={cx('span_overflow_omit')} onClick={() => { updateFileModal(ik.enclosureName,ik,index,'enclosureName') }}>{ik.enclosureName}</span>
                        <span style={{display: (item.id&&actionType == 'check') ? "none" : "block"}} className={cx('red_del_style')} onClick={() => { delEnclosureName('表格数据',item,ik) }}>X</span>
                  </div>
          })}
          </div>
        }else{
          return <Button disabled={actionType == 'check'} onClick={() => { updateEnclosureNameName(value,item,index) }}  type="link">选择</Button>
        }
      }
    },
    {
      title: '备注', dataIndex: 'remark', key: 'remark', width: 200,
      render: function (value, item, index) {
        return <div>
                <Input value = {item.remark} disabled={actionType == 'check'}
                    onChange={(e) => { tableChange(e.target.value, 'remark',item.key) }}
                  />
              </div>
      }
    },
  ]
 
  const gridProps = {
    nameSpace: namespace,
    selectedKeysChange: 'selectedKeysChange',
    data: {
      columns: columns1
      ,
      pageConfig, tableData, selectedRowKeys,
    },
    pageChange: (pageNo, pageSize) => {
      tableData = { ...tableData, pageNo, pageSize }
      pageConfig = { ...pageConfig, pageNo, pageSize }
      changeState({ tableData, pageConfig });
    },
    scroll: { x: 2800 },
    loading
  }

  // 业态
  const columns2 = [
    {
      title: '序号', dataIndex: 'ruleNo', key: 'ruleNo',width:100,
      render: function (value, item, index) {
        return index+1
      }
    }, 
    {
      title: '业态名称', dataIndex: 'productName', key: 'productName',
      render: function (value, item, index) {
        return item.productName
      }
    }
  ]
  let selectedRowKeysTemp =  tableData.dataSource.length?tableData.dataSource.filter(item =>item.key == formatsKey)[0]:{}
  let productSelectedKeys = selectedRowKeysTemp&&selectedRowKeysTemp.productSelectedKeys?selectedRowKeysTemp.productSelectedKeys:[]
  let gridProps1 = {
    nameSpace: namespace,
    selectedKeysChange: 'selectedKeysChange1',
    data: {
      columns: columns2,
      pageConfig:productPageConfig, tableData:productListObj,
      selectedRowKeys: productSelectedKeys,
    },
    pageChange: (pageNo, pageSize) => {
      productListObj.pageNo = pageNo
      productListObj.pageSize = pageSize
      productPageConfig.pageNo = pageNo
      productPageConfig.pageSize = pageSize
      tableData = productListObj
      pageConfig = productPageConfig
      changeState({ productListObj, productPageConfig});
    },
    scroll: { x: 800 },
    loading
  }

  //修改状态
  const changeState = (payload) => {
    dispatch({
      type: `${namespace}/updateStore`,
      payload: { ...payload }
    })
  }
 //自定义日期范围的约束函数
  function disabledDate(current) {
    return current < moment(detail.startTime)|| current > moment(detail.endTime)
  }
  //获取分析公司名称
  function onQueryAgent(){
    dispatch({
      type: `${namespace}/queryAgent`,
      payload: {}
    })
  }
  //详情页跳转
  function routerGo() {
    hashHistory.push({
      pathname: '/home/commissions/commissionsDistRules',
      query: {}
    })
  }
  //关闭
  function onCancel(){
    routerGo()
  }
  // 保存
  function save(type) {
    submitType = type
    validateFieldsAndScroll((err) => {
      if (err) {
        return false
      } else {
        dispatch({
          type: `${namespace}/updateStore`,
          payload: {submitType}
        })
        dispatch({
          type: `${namespace}/create`,
          payload: {}
        })
      }
    })
  }
  //项目名称弹窗事件 
  function updateProjectName(){
    projectModalObj.visible = !projectModalObj.visible
    changeState({ projectModalObj})
  }
  function confirmProject(){
    detail.projectName = biz2.selectedRows[0]?biz2.selectedRows[0].projectName:''
    detail.projectId = biz2.selectedRows[0]?biz2.selectedRows[0].projectId:''
    detail.regionName = biz2.selectedRows[0]?biz2.selectedRows[0].regionName:''
    dispatch({
      type: `${namespace}/updateStore`,
      payload: {detail}
    })
    updateProjectName()
  }

  //业态名称弹窗事件
  function updateFormatsName(value,item,index){
    formatsModalObj.visible = !formatsModalObj.visible
    if(item){
      formatsKey = item.key
    }
    changeState({ formatsModalObj,formatsKey})
  }
  function confirmFormats(){
    for(var item of tableData.dataSource){
      if(item.key == formatsKey){
        let list = item.productSelectedRows.length?item.productSelectedRows.map(itt =>{
          return {
            productName: itt.productName,
            productId: itt.productId
          }
        }):[]
        // for(var itp of list){
        //   for(var ipt of item.productList){
        //     if(itp.productId == ipt.productId){
        //       itp.falg = 1
        //     }
        //   }
        // }
        // list = list.filter(ppt =>ppt.falg !=1)
        // item.productList.push(...list)
        item.productList = list
        let name1 = item.productSelectedRows.length?item.productSelectedRows.map(itt =>{
          return itt.productName
        }).join(','):''
        // item.productName = item.productName?item.productName + "," + name1:name1
        item.productName = name1
        // let productNameList = item.productName.split(',')
        // productNameList = [...new Set(productNameList)]
        // item.productName = productNameList.join(',')
      }
    }
    dispatch({
      type: `${namespace}/updateStore`,
      payload: {tableData}
    })
    updateFormatsName()
  }
  // 搜索
  function inputSearch (value, name) {
    let obj = {[name]: value}
    searchData = Object.assign(searchData, obj)
    dispatch({
      type: `${namespace}/updateStore`,
      payload: {searchData}
    })
  }
  function searchFun(){
    productListObj.dataSource = productDataList
    productListObj.dataSource = productListObj.dataSource.filter(item => item.productName.includes(searchData.productName))
    dispatch({
      type: `${namespace}/updateStore`,
      payload: {productListObj}
    })
  }
  function clearFun(){
    searchData.productName = ''
    productListObj.dataSource = productDataList
    dispatch({
      type: `${namespace}/updateStore`,
      payload: {productListObj,searchData}
    })
  }


  //合同编号弹窗事件
  function updateCodeName(value,item,index){
    codeModalObj.visible = !codeModalObj.visible
    if(item){
      formatsKey = item.key
    }
    changeState({ codeModalObj,formatsKey})
  }
  function confirmCodeName(){
    for(var item of tableData.dataSource){
      if(item.key == formatsKey){
        // item.contractId = biz3.selectedRows[0]?biz3.selectedRows[0].documentDesc:''
        item.contractList = biz3.selectedRows.length?biz3.selectedRows.map(item =>{
          return {
            ruleDetailId:'',
            contractId:item.documentDesc,
            contractAnnex:item.annex,
          }
        }):[]
      }
    }
    if(!formatsKey&&formatsKey!==0){
      // detail.contractId = biz3.selectedRows[0]?biz3.selectedRows[0].documentDesc:''
      // detail.contractAnnex = biz3.selectedRows[0]&&biz3.selectedRows[0].annex?biz3.selectedRows[0].annex:''
      detail.contractList = biz3.selectedRows.length?biz3.selectedRows.map(item =>{
        return {
          ruleDetailId:'',
          contractId:item.documentDesc,
          contractAnnex:item.annex,
        }
      }):[]
    }
    dispatch({
      type: `${namespace}/updateStore`,
      payload: {tableData,detail}
    })
    updateCodeName()
  }
  function delCodeName(type,item,it){
    if(item&&type=="表格数据"){
      for(var itemed of tableData.dataSource){
        if(itemed.key == item.key){
          itemed.contractList = itemed.contractList.filter(tt => tt.contractId != it.contractId)
        }
      }
    }
    if(type=="特例规则"){
      // detail.contractId = ''
      // detail.contractAnnex = ''
      detail.contractList = detail.contractList.filter(kk => kk.contractId != item.contractId)
    }
    dispatch({
      type: `${namespace}/updateStore`,
      payload: {tableData,detail}
    })
  }


  //关联附件弹窗
  function updateEnclosureNameName(value,item,index){
    if(!detail.projectId){
      message.warn('请先选择项目名称')
      return false
    }
    enclosureNameModalObj.visible = !enclosureNameModalObj.visible
    if(item){
      formatsKey = item.key
    }
    changeState({ enclosureNameModalObj,formatsKey})
  }
  function confirmEnclosureNameName(){
    for(var item of tableData.dataSource){
      if(item.key == formatsKey){
        
        item.enclosureList = biz4.selectedRows.length?biz4.selectedRows.map(item =>{
            return {
              ruleDetailId:'',
              enclosureId:item.id,
              enclosureUrl:item.aliOssUrl,
              enclosureName:item.fileName
            }
          }):[]
      }
    }
    if(!formatsKey&&formatsKey!==0){
      detail.enclosureList = biz4.selectedRows.length?biz4.selectedRows.map(item =>{
        return {
          ruleDetailId:'',
          enclosureId:item.id,
          enclosureUrl:item.aliOssUrl,
          enclosureName:item.fileName
        }
      }):[]
    }
    dispatch({
      type: `${namespace}/updateStore`,
      payload: {tableData,detail}
    })
    updateEnclosureNameName()
  }
  function delEnclosureNameName(){
    let id = biz4.selectedRows[0]?biz4.selectedRows[0].id:''
    dispatch({
      type: `${namespace}/delFile`,
      payload: {fileId:id}
    })
    updateEnclosureNameName()
  }
  function delEnclosureName(type,item,it){
    if(item&&type=="表格数据"){
      for(var itemed of tableData.dataSource){
        if(itemed.key == item.key){
          itemed.enclosureList = itemed.enclosureList.filter(tt => tt.enclosureId != it.enclosureId)
        }
      }
    }
    if(type=="特例规则"){
      // detail.enclosureName = ''
      // detail.enclosureUrl = ''
      // detail.enclosureId = ''
      detail.enclosureList = detail.enclosureList.filter(kk => kk.enclosureId != item.enclosureId)
    }
    dispatch({
      type: `${namespace}/updateStore`,
      payload: {tableData,detail}
    })
  }
  function updateFileModal(value,item,index,type){
    if(type == 'contractId'){
      return false
    }else if(type == 'enclosureName'){
      url = item.enclosureUrl
      if(value.endsWith('.docx')||value.endsWith('.xlsx')||value.endsWith('.doc')||value.endsWith('.xls')){
        url = 'https://view.officeapps.live.com/op/view.aspx?src=' + url
      }
    }
    fileModalObj.visible = !fileModalObj.visible
    changeState({ fileModalObj,url})
  }

  // 添加
  function updateModal() {
    
    tableObj.key = ++keys
    tableObj.endTime = detail.endTime
    tableObj.startTime = detail.startTime
    let obj = JSON.parse(JSON.stringify(tableObj))
    tableData.dataSource.push(obj)
    changeState({ tableData,keys})
    debugger
  }
  // 复制操作
  function copyModal() {
    let arr = []
    tableData.dataSource.map((item, index) => {
      delete item.id
      if (selectedRowKeys.indexOf(item.key) != -1) {
        let obj = JSON.parse(JSON.stringify(item))
        arr.push(obj)
      }
    })
    for(var item of tableData.dataSource){
      for(var itemed of arr){
        if(item.key == itemed.key){
          itemed.key = keys++
        }
      }
    }
    changeState({ tableData ,keys})
    tableData.dataSource = tableData.dataSource.concat(arr)
  }
  //批量删除选中项
  function deleteItems() {
    let arr = []
    tableData.dataSource.map((item, index) => {
      if (selectedRowKeys.indexOf(item.key) == -1) {
        arr.push(item)
      }
    })
    tableData.dataSource = arr
    tableData.total = tableData.dataSource.length
    debugger
    changeState({ tableData })
  }
  //表单改变时
  function inputChange (value, name) {
    let obj = {[name]: value}
    detail = Object.assign(detail, obj)
    if(name == 'startTime'){
      tableObj.startTime = value
      dispatch({
        type: `${namespace}/updateStore`,
        payload: {detail,tableObj}
      })
    }else if(name == 'endTime'){
      tableObj.endTime = value
      dispatch({
        type: `${namespace}/updateStore`,
        payload: {detail,tableObj}
      })
    }else{
      dispatch({
        type: `${namespace}/updateStore`,
        payload: {detail}
      })
    }
  }
  //特例规则
  function checkboxChange(value, name){
    let val = ''
    value?val = 1:val = 0
    let obj = {[name]: val}
    detail = Object.assign(detail, obj)
    dispatch({
      type: `${namespace}/updateStore`,
      payload: {detail}
    })
  }
  //表格改变时
  function tableChange (value, name,id) {
    let obj = {[name]: value}
    for(var item of tableData.dataSource){
      if(item.key == id){
        item = Object.assign(item, obj)
      }
    }
    dispatch({
      type: `${namespace}/updateStore`,
      payload: {tableData}
    })
  }
  function tableChangeCommType(value, name,id){
    let obj = {[name]: value}
    for(var item of tableData.dataSource){
      if(item.key == id){
        item.amount = ''
        item.ratioNum = ''
        item.numberStart = ''
        item.numberEnd = ''
        item.amountStart = ''
        item.amountEnd = ''
        item = Object.assign(item, obj)
        if(value == '按套数跳点'){
          item.commType = 1
        }else if(value == '按金额跳点'){
          item.commType = 2
        }else if(value == '按固定金额'){
          item.commType = 3
        }else if(value == '按固定比例'){
          item.commType = 4
        }else if(value == '按套数跳固额'){
          item.commType = 5
        }
      }
    }
    dispatch({
      type: `${namespace}/updateStore`,
      payload: {tableData}
    })
  }
  //赋值distCoId
  function tableChangeDistCoId (value, name,id) {
    let obj = {[name]: value}
    for(var item of distributionNameList){
        if(item.orgName == value){
          distCoId = item.orgId
        }
    }
    for(var item of tableData.dataSource){
      if(item.key == id){
        item = Object.assign(item, obj)
        item['distCoId'] = distCoId
      }
    }
    dispatch({
      type: `${namespace}/updateStore`,
      payload: {tableData}
    })
  }
  //上传附件
  function updateUploadModal(){
    if(!detail.projectId){
      message.warn('请先选择项目名称')
      return false
    }
    uploadFileObj.visible=!uploadFileObj.visible
    changeState({uploadFileObj})
  }
  function removeImgUrl(index){
    imageUrls.splice(index, 1)
    dispatch({
        type: `${namespace}/updateStore`,
        payload: { imageUrls }
    })
  }
  function updateImageModel(value,fileObj) {
    imageUrls[0]={
        url:value,
        name:fileObj.name,
    };
    // 分发到model
    dispatch({
        type: `${namespace}/updateStore`,
        payload: { imageUrls }
    })
  };

  if (!!modelObj.biz2) {
    pageProps2.biz = modelObj.biz2
    pageProps2.biz.syncBackCbf = (biz) => {
      dispatch({
        type: `${namespace}/updateStore`,
        payload: { biz2:biz }
      })
    }
  }
  if (!!modelObj.biz3) {
    pageProps3.biz = modelObj.biz3
    pageProps3.biz.syncBackCbf = (biz) => {
      dispatch({
        type: `${namespace}/updateStore`,
        payload: { biz3:biz }
      })
    }
  }
  if (!!modelObj.biz4) {
    pageProps4.biz = modelObj.biz4
    pageProps4.biz.syncBackCbf = (biz) => {
      dispatch({
        type: `${namespace}/updateStore`,
        payload: { biz4:biz }
      })
    }
  }
  return (
    <div className={cx('public_listMain')}>
      <div className="functionButton">
      <Button disabled={actionType == 'check'} type='primary' loading={modelObj.btnLoading} onClick={() => { save('提交审批') }}>提交审批</Button>
        <Button disabled={actionType == 'check'} type='primary' onClick={() => { save() }}>保存</Button>
        <Popconfirm  disabled={actionType == 'check'} placement="top" title={"是否确认关闭，确认后关闭页面，不保存数据。"} onConfirm={() => onCancel()} okText="确定" cancelText="取消">
          <Button>关闭</Button>
        </Popconfirm>
      </div>
      <CollapsiblePanels title="佣金规则" hideUpDownBtn={true}>
        <Row>
          <Col className="col" span={8}>
            <FormItem {...formItemLayout}
              label="佣金方案名称">
              {getFieldDecorator('name', {
                initialValue: detail.name,
                rules: [
                  { required: true, whitespace: true, message: '项目+年月+佣金规则方案' },
                ],
              })(<Input disabled={actionType == 'check' }
                placeholder={'项目+年月+佣金规则方案'}
                onChange={(e) => { inputChange(e.target.value, 'name') }}
              />)}
            </FormItem>
          </Col>
          <Col className="col" span={8}>
            <FormItem {...formItemLayout}
              label="版本号">
              {getFieldDecorator('version', {
                initialValue: detail.version?'V' + detail.version: '',
                rules: [
                  { required: false, whitespace: true, message: '请输入版本号' },
                ],
              })(<Input  disabled={true}
                onChange={(e) => { inputChange(e.target.value, 'version') }}
              />)}
            </FormItem>
          </Col>
        </Row>
        <Row>
        <Col className="col" span={8}>
            <FormItem {...formItemLayout}
              label="项目名称">
              {getFieldDecorator('projectName', {
                initialValue: detail.projectName,
                rules: [
                  { required: true, whitespace: true, message: '请输入项目名称', },
                ],
              })(<Input disabled={actionType == 'check'} readOnly={true}
                placeholder={'请输入项目名称'}
                onChange={(e) => { inputChange(e.target.value, 'projectName') }}
                onClick={() => { updateProjectName() }}
              />)}
            </FormItem>
          </Col>
          <Col className="col" span={8}>
            <FormItem label='佣金计算节点'  {...formItemLayout}>
                {getFieldDecorator('computeNodes', {
                    rules: [{
                        required: true,whitespace: true, message: '请输入佣金计算节点'
                    }],
                    initialValue: detail.computeNodes+''                    
                })(
                  <Select disabled={actionType == 'check'} placeholder='请选择佣金计算节点' onChange={(e)=>{inputChange(e,'computeNodes')}}>
                      <Select.Option value="1">按签约归属日期</Select.Option>
                      <Select.Option value="2">按认购归属日期</Select.Option>
                      <Select.Option value="3">按网签日期</Select.Option>
                  </Select>
                )}
            </FormItem>
          </Col>
        </Row>
        <Row>
          <Col className="col" span={8}>
              <FormItem
                  {...formItemLayout}
                  label="方案生效日期"
                  >
                  {getFieldDecorator('startTime', {
                    rules:[{required:true,message:'请选择方案生效时间'},],
                    initialValue: detail.startTime ? moment(detail.startTime, 'YYYY-MM-DD') : null
                  })(
                    <DatePicker disabled={actionType == 'check'} format="YYYY-MM-DD" onChange={(e, val) => inputChange(val, 'startTime')}  />
                  )}
              </FormItem>
          </Col>
          <Col className="col" span={8}>
              <FormItem
                  {...formItemLayout}
                  label="方案失效日期"
                  >
                  {getFieldDecorator('endTime', {
                    rules:[{required:true,message:'请选择方案失效时间'},],
                    initialValue: detail.endTime ? moment(detail.endTime, 'YYYY-MM-DD') : null
                  })(
                    <DatePicker disabled={actionType == 'check'} format="YYYY-MM-DD" onChange={(e, val) => inputChange(val, 'endTime')}  />
                  )}
              </FormItem>
          </Col>
        </Row>
        <Row>
          <Col span={16}>
            <FormItem {...formItemLayout01}
              label="备注">
              {getFieldDecorator('remark', {
                initialValue: detail.remark,
                rules: [
                  { required: false, whitespace: true, message: '', },
                ],
              })(
              <TextArea disabled={actionType == 'check'} style={{width:500}} onChange={e=>{inputChange(e.target.value,'remark')}}></TextArea>
              )}
            </FormItem>
          </Col>
        </Row> 
        <div style={{marginBottom:'12px'}}><Col span={2}></Col><Checkbox checked={detail.noCommission} disabled={actionType == 'check'} onChange={e=>{checkboxChange(e.target.checked,'noCommission')}}>特例规则</Checkbox></div>
        <Row style={{display:detail.noCommission?'block': 'none'}}>
          <Col span={24} style={{display:'flex',padding:'0 4%'}}>
            <FormItem {...formItemLayout01}
              label="规则说明">
              {getFieldDecorator('noCommissionRemark', {
                initialValue: detail.noCommissionRemark,
                rules: [
                  { required: detail.noCommission?true:false, whitespace: true, message: '请输入规则说明', },
                  {max: 1000,message: "最多输入1000个字符",}
                ],
              })(
              <TextArea disabled={actionType == 'check'}  style={{width:500}} onChange={e=>{inputChange(e.target.value,'noCommissionRemark')}}></TextArea>
              )}
            </FormItem>
          <div style={{marginTop:'12px',marginLeft:'8px',color:'#0877fd',fontSize:'16px',zIndex:99,display:'flex'}}>
            <span onClick={() => { updateCodeName() }} style={{cursor:'pointer'}}>关联合同</span>
            { detail.contractList == undefined ?null:detail.contractList.map((itemed,keyy)=>{
             return <div style={{marginLeft: '12px'}}  className={cx('flex')} key={keyy}>
                  <span style={{cursor: 'pointer'}} onClick={() => { updateFileModal('','','','contractId') }}>{itemed.contractId}</span>
                  <span style={{display: (actionType == 'check') ? "none" : "inline-block"}} className={cx('red_del_style')}  onClick={() => { delCodeName('特例规则',itemed) }}>X</span>
              </div>
            })}
            <span onClick={() => { updateEnclosureNameName() }} style={{marginLeft: '16px',cursor:'pointer'}}>关联附件</span>
            { detail.enclosureList == undefined ?null:detail.enclosureList.map((item,key)=>{
            return <div style={{marginLeft: '12px'}} className={cx('flex')} key={key}>
                    <span style={{cursor: 'pointer'}} onClick={() => { updateFileModal(item.enclosureName,item,'','enclosureName') }}>{item.enclosureName}</span>
                    <span style={{display: (actionType == 'check') ? "none" : "inline-block"}} className={cx('red_del_style')} onClick={() => { delEnclosureName('特例规则',item) }}>X</span>
                  </div>
            })}
          </div>
          </Col>
        </Row> 
      </CollapsiblePanels>

      <CollapsiblePanels title="佣金规则明细" hideUpDownBtn={true} >
        <div className="clearfix mgb1">
          <div className={cx('fr')}>
            <Button  disabled={actionType == 'check'||detail.noCommission} type='primary' onClick={() => { updateModal() }}>添加</Button>
            <Button  disabled={actionType == 'check'||detail.noCommission} type='primary' className='mgl1' onClick={(e) => {
              copyModal()
            }}>复制</Button>
            <Popconfirm placement="top" title={"确定删除选中项吗？"} onConfirm={() => deleteItems()} okText="确定" cancelText="取消">
              <Button type='primary'  disabled={actionType == 'check'||detail.noCommission} className='mgl1'>删除</Button>
            </Popconfirm>
            <Button  disabled={actionType == 'check'} type='primary'  className='mgl1' onClick={() => { updateUploadModal() }}>上传附件</Button>
          </div>
        </div>
        <div className={cx('mt1', 'table_projectList')} style={{display:detail.noCommission?'none': 'block'}}>
          <Form>
            <Grid {...gridProps}/>
          </Form>
        </div>
      </CollapsiblePanels>
        {/*选择项目弹窗*/}
        <Modal
        title={'所属项目'}
        width='1000px'
        // destroyOnClose={true}
        visible={projectModalObj.visible}
        onCancel={() => { updateProjectName() }}
        onOk={() => { confirmProject() }}
      >
        <div>
            <ListPage pageProps={pageProps2}/>
        </div>
      </Modal>
        {/*新销售系统业态档案弹窗*/}
        <Modal
          title={'新销售系统业态档案'}
          width='800px'
          destroyOnClose={true}
          visible={formatsModalObj.visible}
          onCancel={() => { updateFormatsName() }}
          onOk={() => { confirmFormats() }}
        >
          <div>
              {/* <ListPage pageProps={pageProps1}/> */}
              <div style={{marginBottom:'12px'}}>
                  <Row>
                    <Col span={2} style={{lineHeight:'28px'}}>
                    <label>业态名称</label>:
                    </Col>
                    <Col span={6} style={{marginRight:'10px'}}>
                    <Input  value ={searchData.productName} placeholder="请输入业态名称" onChange={(e) => { inputSearch(e.target.value, 'productName') }}/>
                    </Col>
                    <Col span={8}></Col>
                    <Col span={6}>
                      <Button type='primary' onClick={() => {searchFun()}}>查询</Button>
                      <Button style={{marginLeft: '12px'}} onClick={() => {clearFun()}}>重置</Button>
                    </Col>
                  </Row>
                </div>     
              <Grid {...gridProps1} />
          </div>
        </Modal>
        {/*合同编号弹窗*/}
        <Modal
          title={'合同编号'}
          width='1000px'
          destroyOnClose={true}
          visible={codeModalObj.visible}
          onCancel={() => { updateCodeName() }}
          onOk={() => { confirmCodeName() }}
        >
          <div className={''}>
              <ListPage pageProps={pageProps3}/>
          </div>
        </Modal>
        {/* 关联附件弹窗 */}
        <Modal
        title={'附件列表'}
        width='1000px'
        destroyOnClose={true}
        visible={enclosureNameModalObj.visible}
        onCancel={() => { updateEnclosureNameName() }}
        footer={null}
      >
        <div className={''}>
            <ListPage pageProps={pageProps4}/>
            <div style={{textAlign: 'right'}}>
                <Button  onClick={() => {updateEnclosureNameName() }}>取消</Button>
                <Popconfirm placement="top" title={"确定删除选中项吗？"} onConfirm={() => delEnclosureNameName()} okText="确定" cancelText="取消">
                  <Button type='primary' style={{margin: '0 12px'}}>删除</Button>
                </Popconfirm>
                <Button type='primary'  onClick={() => {confirmEnclosureNameName()}}>确认</Button>
            </div>
        </div>
      </Modal>
        {/* 上传附件弹窗 */}
        <Modal title={'上传附件列表'}
                visible={uploadFileObj.visible}
                okText={'导入'}
                destroyOnClose={true}
                cancelText={'取消'}
                confirmLoading={uploadFileObj.confirmLoading}
                onCancel={() => {
                    updateUploadModal()
                }}
                onOk={() => {
                    dispatch({
                        type: `${namespace}/importAccount`,
                        payload: {}
                    });
                }}
                width={720}>
            <div className={styles.modalCss}>
                <Form>
                    <Row>
                        <Col span={24}>
                            <FormItem label={'文件'}>
                            <Uploader
                                    uploadedUrls={imageUrls}
                                    removeFileCbf={(index) => { removeImgUrl(index) }}
                                    uploadSuccessCbf={(imgUrl,fileObj) => { updateImageModel(imgUrl,fileObj) }}
                                    showType='5'
                                    accept={'.xlsx,.xls,.doc,.docx,.pdf,.txt'}
                                    // uploadTip='支持*.xlsx, *.xls格式文件。'
                                    uploadTip='支持*.doc, *.docx, *.pdf, *.xlsx, *.xls, *.txt格式文件。'
                                    fileType='file'
                                    maxFiles='50'
                                />
                            </FormItem>
                        </Col>
                    </Row>
                </Form>
            </div>
        </Modal>
        {/*查看附件*/}
        <Modal
        width='1000px'
        visible={fileModalObj.visible}
        destroyOnClose={true}
        onCancel={() => { updateFileModal() }}
        footer={null}
      >
        <div>
          <iframe id="fileSeck" name="fileSeck" width="950" height="500"  src={url}></iframe>
        </div>
      </Modal>
    </div>
  )
}

// 连接视图(view)和模型(model)
export default connect(mapStateToProps)(Form.create()(commissionsDistRulesDetailView))
